package cn.cvs.servlet;

import cn.cvs.dao.ResumeMapper;
import cn.cvs.pojo.Resume;
import cn.cvs.utils.MyBatisUtil;
import org.apache.ibatis.session.SqlSession;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

@WebServlet(urlPatterns = "/ResumeAdd")
public class ResumeAdd extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("utf-8");
        response.setContentType("text/html;charset=utf-8");
        SqlSession sqlSession = MyBatisUtil.createSqlSession();
        ResumeMapper resumeMapper = sqlSession.getMapper(ResumeMapper.class);
        Resume resume = new Resume();
        resume.setUserName(request.getParameter("userName"));
        resume.setSex(request.getParameter("sex"));
        resume.setBirth(request.getParameter("birth"));
        resume.setAddress(request.getParameter("address"));
        resume.setTelephone(request.getParameter("telephone"));
        resume.setSchool(request.getParameter("school"));
        resume.setStatus(Integer.parseInt(request.getParameter("status")));
        int resule = 0;
        try{
            resule = resumeMapper.add(resume);
            sqlSession.commit();
        }catch (Exception ex){
            ex.printStackTrace();
            sqlSession.rollback();
        }finally {
            MyBatisUtil.closeSqlSession(sqlSession);
        }
        PrintWriter out = response.getWriter();
        if (resule > 0){
            out.print("<script>\n" +
                    "    location.href='ResumeListServlet';\n" +
                    "    alert('添加成功!')\n" +
                    "  </script>");
        }else {
            out.print("<script>\n" +
                    "    location.href='ResumeListServlet';\n" +
                    "    alert('添加失败!')\n" +
                    "  </script>");
        }
        out.flush();
        out.close();
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }
}
